<template>
  <a-dropdown :trigger="['click']" v-model="show">
    <div slot="overlay">
      <a-spin :spinning="loading">
        <a-tabs class="dropdown-tabs" :tabBarStyle="{textAlign: 'center'}" :style="{width: '297px'}">
          <a-tab-pane tab="通知" key="1">
            <a-list ref="inform" class="tab-pane">
              <a-list-item v-for="(item, index) in notifications" :key="index">
                <a-list-item-meta
                    :title="item.title"
                    :description="item.description"
                >
                  <a-avatar
                      style="background-color: white"
                      slot="avatar"
                      :src="item.avatarUrl"
                  />
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
          <a-tab-pane tab="消息" key="2">
            <a-list class="tab-pane">
              <a-list-item v-for="(item, index) in filteredChatList" :key="index">
                <a-list-item-meta :title="filteredChatList[index].num + '条消息'"
                                  :description="filteredChatList[index].time">
                  <a-avatar style="background-color: white" slot="avatar"
                            :src="avatarUrl.avatar ||  Url+'/api/uploads/default_avatar.png'"/>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
          <a-tab-pane tab="待办" key="3">
            <a-list class="tab-pane">
              <a-list-item v-if="order.num !== 0">
                <a-list-item-meta :title="'你收到了 '+order.num+' 份发货通知'" :description="order.time">
                  <a-avatar style="background-color: white" slot="avatar"
                            src="https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png"/>
                </a-list-item-meta>
              </a-list-item>
              <a-list-item v-if="orderafter.num !== 0">
                <a-list-item-meta :title="'你收到了 '+orderafter.num+' 份售后通知'" :description="orderafter.time">
                  <a-avatar style="background-color: white" slot="avatar"
                            src="https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png"/>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </div>
    <span @click="fetchNotice" class="header-notice">
      <a-badge class="notice-badge" :count="this.HeadersNum">
        <a-icon :class="['header-notice-icon']" type="bell"/>
      </a-badge>
    </span>
  </a-dropdown>
</template>

<script>
import axios from "axios";

export default {
  name: 'HeaderNotice',
  data() {
    return {
      loading: false,
      show: false,
      Url: `${window.location.protocol}//${window.location.hostname}:8080`,
      HeadersNum: 0, // 初始值
      order: {
        num: 0,
        time: '12-1-1 15:15:00'
      },
      orderafter: {
        num: 0,
        time: '12-1-1 15:15:00'
      },
      ChatList: [],
      notifications: [  // 预先加载的数据
        {
          title: '你收到了 1 份钉钉通知',
          description: new Date().toLocaleString(),
          avatarUrl: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png'
        },
      ],
      avatarUrl: null
    }
  },
  computed: {
    filteredChatList() {
      // 过滤掉 num 为 0 的项
      return this.ChatList.filter(item => item.num !== 0);
    }
  },
  mounted() {
    this.fetchOrdernum()
    this.fetchOrderAfterInfo()
    this.fetchChatInfo()
    this.startTimeUpdate()
    this.fetchavatarUrl()
    // this.updatePageView();
  },
  methods: {
    fetchavatarUrl() {
      this.avatarUrl = localStorage.getItem('admin.user')
    },
    // 每10秒获取一次 localStorage 中的值
    startTimeUpdate() {
      setTimeout(() => {
        this.HeadersNum =
            parseInt(this.order.num === 0 ? 0 : this.order.num) +
            parseInt(this.orderafter.num === 0 ? 0 : this.orderafter.num) +
            parseInt(this.filteredChatList.length > 0 && this.filteredChatList[0] ? this.filteredChatList[0].num : 0) +
            parseInt(this.notifications.length === 0 ? 0 : this.notifications.length);
      }, 500)
    },
    // timeUpdate() {
    //   // 从 localStorage 获取存储的值
    //   const savedPageView = localStorage.getItem('HeadersNum');
    //   if (savedPageView) {
    //     this.pageView = parseInt(savedPageView, 10); // 设置为从 localStorage 获取的值
    //   }
    // },
    // updatePageView() {
    //   let backloglength = 0;
    //   let informlength = 0;
    //   let informationlength = 0;
    //
    //   if (this.$refs.backlog && this.$refs.backlog.$el) {
    //     backloglength = this.$refs.backlog.$el.querySelectorAll('.ant-list-item').length;
    //     let HeadersBackLogLengThNum = localStorage.getItem('HeadersBackLogLengThNum')
    //     if (backloglength != 0) {
    //       if (backloglength >= 0 && HeadersBackLogLengThNum != backloglength) {
    //         localStorage.setItem('HeadersBackLogLengThNum', backloglength)
    //       } else {
    //         backloglength = HeadersBackLogLengThNum
    //       }
    //     } else {
    //       localStorage.setItem('HeadersBackLogLengThNum', backloglength)
    //     }
    //   }
    //
    //   if (this.$refs.inform && this.$refs.inform.$el) {
    //     informlength = this.$refs.inform.$el.querySelectorAll('.ant-list-item').length;
    //     let HeadersInformLengthThNum = localStorage.getItem('HeadersInformLengthThNum')
    //     if (informlength != 0) {
    //       if (informlength >= 0 && HeadersInformLengthThNum != informlength) {
    //         localStorage.setItem('HeadersInformLengthThNum', informlength)
    //       } else {
    //         informlength = HeadersInformLengthThNum
    //       }
    //     } else {
    //       localStorage.setItem('HeadersInformLengthThNum', informlength)
    //     }
    //   }
    //
    //   if (this.$refs.information && this.$refs.information.$el) {
    //     informationlength = this.$refs.information.$el.querySelectorAll('.ant-list-item').length;
    //     let HeadersInformationLengthNum = localStorage.getItem('HeadersInformationLengthNum')
    //     if (informationlength != 0) {
    //       if (informationlength >= 0 && HeadersInformationLengthNum != informationlength) {
    //         localStorage.setItem('HeadersInformationLengthNum', informationlength)
    //       } else {
    //         informationlength = HeadersInformationLengthNum
    //       }
    //     } else {
    //       localStorage.setItem('HeadersInformationLengthNum', informationlength)
    //     }
    //   }
    //
    //   // 更新 localStorage 存储的值
    //   let HeadersNums = parseInt(backloglength) + parseInt(informlength) + parseInt(informationlength);
    //   let HeadersNum = localStorage.getItem('HeadersNum');
    //   if (HeadersNum != 0) {
    //     this.HeadersNum = localStorage.getItem('HeadersNum')
    //   } else if (HeadersNum == 0) {
    //     this.HeadersNum = HeadersNums;
    //     localStorage.setItem('HeadersNum', this.HeadersNum);
    //   }
    //
    // },
    // 获取订单信息
    async fetchOrdernum() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/order/infoidOrderAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          this.order.num = response.data.data.filter(item => item.expressIs === '未发货').length
          // const time = response.data.data.filter(item => item.expressIs === '未发货').reverse()
          this.order.time = new Date().toLocaleString();
        } else {
          console.error('获取订单信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchOrderAfterInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/orderafter/infoorderafterall`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          this.orderafter.num = response.data.data.filter(item => item.afterStatus === '售后中').length
          // const time = response.data.data.filter(item => item.afterStatus === '售后中').reverse()
          this.orderafter.time = new Date().toLocaleString();
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchChatInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/messages/getAll`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          // 获取原始数据
          const data = response.data.data;

          // 过滤出 merchantId 不为空的项
          const filteredData = data.filter(item => item.merchantName === null);

          // 使用 reduce 对数据按 userName 分组，并统计每组的消息数量和时间
          this.ChatList = filteredData.reduce((groups, item) => {
            // 查找当前分组中是否已有相同 userName 的项
            const group = groups.find(group => group.userName === item.userName);

            if (group) {
              // 如果找到了相同的 userName，将消息数量加 1，并更新最新时间
              group.num += 1;
              group.time = item.createdTime > group.time ? item.createdTime : group.time;
            } else {
              // 如果没有找到相同的 userName，创建一个新的分组
              groups.push({
                userName: item.userName,
                num: 1,
                time: item.createdTime
              });
            }
            return groups;
          }, []);
          // 获取 localStorage 中保存的 ChatList 数据
          const storedChatList = JSON.parse(localStorage.getItem('ChatList')) || [];

          // 比对 this.ChatList 和 storedChatList，更新消息数量
          this.ChatList.forEach(chatItem => {
            const storedItem = storedChatList.find(stored => stored.userName === chatItem.userName);

            if (storedItem) {
              // 如果在 localStorage 中找到了相同的 userName，减去 localStorage 中保存的 num 值
              chatItem.num -= storedItem.num;
            }
          });
        }
      } catch (error) {
        console.error('Error fetching chat info:', error);
      }
    },
    fetchNotice() {
      if (this.loading) {
        this.loading = false
        return
      }
      if (this.show) return
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 1000)
    }
  }
}
</script>

<style lang="less">
.header-notice {
  display: inline-block;
  transition: all 0.3s;

  span {
    vertical-align: initial;
  }

  .notice-badge {
    color: inherit;

    .header-notice-icon {
      font-size: 16px;
      padding: 4px;
    }
  }
}

.dropdown-tabs {
  background-color: @base-bg-color;
  box-shadow: 0 2px 8px @shadow-color;
  border-radius: 4px;

  .tab-pane {
    padding: 0 24px 12px;
    min-height: 250px;
  }
}
</style>
